<?php
/**
 * Created by PhpStorm.
 * User: xing.chen
 * Date: 2017/8/13
 * Time: 9:56
 */

namespace common\service;

use common\modules\user\User;

class TokenUserService extends TokenService
{

    # 缓存token 时间为2小时，过期如果需要会自动再次缓存2小时
    const EXPIRE_TIME = 7200;
    public static $prefix = 'TU:';

    /**
     * 保存用户token
     * @param $userId
     * @param $token
     */
    public static function set($userId, $token, $expireTime = null)
    {
        parent::set($userId, $token, self::EXPIRE_TIME);
    }
    /**
     * 读取用户token
     * @param $userId
     * @return mixed|null
     */
    public static function get($userId)
    {
        $token = parent::get($userId);
        if (empty($token)) {
            $token = User::getToken($userId);
            if (!empty($token)) parent::set($userId, $token);
        }
        return $token;
    }

    /**
     * 检查token
     * @param $userId
     * @param $token
     * @return bool
     */
    public static function checkToken($userId, $token)
    {
        if (empty($userId) || empty($token)) return false;
        $oldToken = static::get($userId);
        return $oldToken == $token;
    }

}